package dnet

import (
	"fmt"
	"net"
	"time"
)

func SetKeepAlive(conn net.Conn, val bool) error {
	tcp, ok := conn.(*net.TCPConn)
	if ok {
		return tcp.SetKeepAlive(val)
	}
	return fmt.Errorf("unsupport conn")
}

func DialCustom(network, address string, timeout time.Duration, localAddr string) (net.Conn, error) {
	if len(localAddr) == 0 {
		d := net.Dialer{Timeout: timeout}
		return d.Dial(network, address)
	} else {
		if network == "udp" {
			local, err := net.ResolveUDPAddr(network, localAddr)
			if err != nil {
				return nil, err
			}
			d := net.Dialer{Timeout: timeout, LocalAddr: local}
			return d.Dial(network, address)
		} else {
			local, err := net.ResolveTCPAddr(network, localAddr)
			if err != nil {
				return nil, err
			}
			d := net.Dialer{Timeout: timeout, LocalAddr: local}
			return d.Dial(network, address)
		}

	}

}
